package org.example.chapter3.service.iml;

import org.example.chapter3.entity.Student;
import org.example.chapter3.entity.User;
import org.example.chapter3.service.StudentService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceIml  implements StudentService {
    //    @Autowired
    JdbcTemplate jdbcTemplate;

    public StudentServiceIml(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //增加
    @Override
    public int addStudent(Student student) {
        String sql = "insert into student (sname,password) value (?,?)";
        return jdbcTemplate.update(sql,student.getSname(),student.getPassword());
    }

    //删除
    @Override
    public int deleteStudent(int id) {
        String sql = "delete from student where id=?";
        return jdbcTemplate.update(sql,id);
    }

    // 修改
    @Override
    public int updateStudent(Student student) {
        String sql = "update student set sname=?,password=? where id=?";
        Object[] args = {student.getSname(), student.getPassword(), student.getId()};
        return jdbcTemplate.update(sql, args);
    }
    //查询
    @Override
    public Student findStudent(int id) {
        String sql = "select * from student where id=?";
        List<Student> studentList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class), id);
        if (studentList.isEmpty()) {
            // 可以根据具体需求返回null或者抛出自定义的异常，这里返回null作为示例
            return null;
        }
        return studentList.get(0);
    }

}